package com.frp.lib.handler;

import com.frp.lib.client.ClientApi;
import com.frp.lib.message.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by hujianjun on 12/5 0005.
 */
public class ProxyHandler extends SimpleChannelInboundHandler<Message> {
    private static Logger logger = LoggerFactory.getLogger(ProxyHandler.class);
    private String password;
    private ClientApi clientApi;

    public ProxyHandler(String password, ClientApi clientApi) {
        this.password = password;
        this.clientApi = clientApi;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
//        Message.NewWorkConn newWorkConn = new Message.NewWorkConn();
//        newWorkConn.setRun_id(clientApi.getRunId());
//        ctx.writeAndFlush(newWorkConn);
        ctx.read();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("error, will close.", cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
//        logger.info("read msg:{}", msg);
        if (msg instanceof Message.StartWorkConn) {
            this.onStart(ctx, (Message.StartWorkConn)msg);
        } else {
            ctx.close();
        }
    }

    private void onStart(ChannelHandlerContext ctx, Message.StartWorkConn msg) {
        clientApi.onStartWorkConn(ctx, msg);
    }
}
